<script setup lang="ts">
import {
  reqDepAdd,
  reqDepDelete,
  reqDepEdit,
  reqDepList,
  reqDepStatus,
  reqPersonList,
} from "@/api/Department/Department"
import type {
  DepAddParams,
  DepListParams,
  DepResponse,
  DepResponseData,
  DepResultList,
} from "@/api/types/Department"
import { JobPeronsResponse, JobPerosnItems } from "@/api/types/Position"
import { onMounted, reactive, ref } from "vue"

// 搜索内容
const searchValue = ref("")
// 当前页
const current = ref(1)
// 获取条数
const limit = ref(5)
// 对话框显示隐藏
const dialogVisible = ref(false)
// 列表总数量
const total = ref(0)
// 部门列表
const DepartmentList = ref<DepResultList[]>([])
// 控制器
const isWho = ref(1)
// 表单实例
const dialogFormRef = ref()
// 表单数据
const headSelectedPerson = ref("")
const depFormData = reactive({
  _id: "",
  name: "",
  head: headSelectedPerson.value,
})

// 用户人信息列表
const depUserList = ref<JobPerosnItems[]>([])

// 表单校验
const dialogFormRules = {
  name: [{ required: true, message: "部门名称必填", trigger: "blur" }],
  head: [{ required: true, message: "负责人必填", trigger: "blur" }],
}

// 获取用户列表
const getDeparList = async (pages = 1) => {
  current.value = pages
  const params: DepListParams = {
    current: current.value,
    limit: limit.value,
    name: searchValue.value,
  }
  const result: DepResponseData = await reqDepList(params)
  DepartmentList.value = result.data.result
  current.value = Number(result.data.current)
  limit.value = +result.data.limit
  total.value = +result.data.total
}

// 获取用户人列表信息
const getUserList = async () => {
  const result: JobPeronsResponse = await reqPersonList()
  depUserList.value = result.result
}

// 搜索内容
const searchBtn = () => {
  getDeparList()
}
// 重制内容
const reset = () => {
  searchValue.value = ""
  getDeparList()
}

// 对话框关闭事件回掉
const handleClose = () => {
  close()
}
// 新增按钮
const addData = () => {
  isWho.value = 1
  dialogVisible.value = true
  getUserList()
}
// 编辑按钮
const editBtn = (row: DepResultList) => {
  isWho.value = 2
  dialogVisible.value = true
  Object.assign(depFormData, row)
  getUserList()
}
// 删除按钮
const deleteBtn = async (_id: string) => {
  const result: DepResponse = await reqDepDelete(_id)
  if (result.code == 201) {
    ElMessage.success(result.msg)
    getDeparList(current.value)
    return
  }
  ElMessage.error(result.msg)
}

// 修改当前状态
const chnageStatus = async (row: DepResultList) => {
  const result: DepResponse = await reqDepStatus(row._id, row.status)
  if (result.code == 201) {
    ElMessage.success(result.msg)
    getDeparList(current.value)
    return
  }
  ElMessage.error(result.msg)
}

// 对话框关闭
const close = async () => {
  Object.assign(depFormData, {
    _id: "",
    name: "",
    head: "",
  })
  await dialogFormRef.value.clearValidate(["name", "head"])
  dialogVisible.value = false
}
// 数据提交
const save = async () => {
  await dialogFormRef.value.validate()
  if (isWho.value == 1) {
    const params: DepAddParams = {
      name: depFormData.name,
      head: depFormData.head,
    }
    const result: DepResponse = await reqDepAdd(params)
    if (result.code == 201) {
      ElMessage.success(result.msg)
      close()
      getDeparList(current.value)
      return
    }
    ElMessage.error(result.msg)
  }
  if (isWho.value == 2) {
    const result: DepResponse = await reqDepEdit(depFormData)
    if (result.code == 201) {
      ElMessage.success(result.msg)
      getDeparList(current.value)
      close()
      return
    }
    ElMessage.error(result.msg)
  }
}

// 分页起当页数
const handleSizeChange = () => {
  getDeparList()
}
onMounted(() => {
  getDeparList()
})
</script>

<template>
  <div class="Department">
    <el-card>
      <el-row>
        <el-col :span="8" v-has="`Department.btn.query`">
          <el-input v-model="searchValue" placeholder="请输入搜索部门" />
          <el-button
            :disabled="searchValue.length > 0 ? false : true"
            type="primary"
            @click="searchBtn"
            >搜索</el-button
          >
          <el-button
            :disabled="searchValue.length > 0 ? false : true"
            type="info"
            @click="reset"
            >重置</el-button
          >
        </el-col>
        <el-col :span="3">
          <el-button v-has="`Department.btn.add`" type="primary" @click="addData">新增部门</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <el-table border :data="DepartmentList">
        <el-table-column label="#" type="index" width="50" align="center" />
        <el-table-column label="部门名称" prop="name" align="center" />
        <el-table-column label="负责人" prop="head" align="center" />
        <el-table-column v-has="`Department.btn.status`" label="状态" align="center">
          <template #="{ row }">
            <el-switch
              @change="chnageStatus(row)"
              v-model="row.status"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="createTime"
          width="180"
          align="center"
        />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          width="180"
          align="center"
        />
        <el-table-column label="操作" width="200">
          <template #="{ row }">
            <el-button
              v-has="`Department.btn.edit`"
              size="small"
              @click="editBtn(row)"
              type="primary"
              icon="Edit"
            ></el-button>
            <el-popconfirm
              title="确认删除该部门?"
              @confirm="deleteBtn(row._id)"
            >
              <template #reference>
                <el-button v-has="`Department.btn.delete`" size="small" type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:current-page="current"
        v-model:page-size="limit"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="prev, pager, next, total, ->,sizes,jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getDeparList"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      title="Tips"
      width="600"
      :before-close="handleClose"
    >
      <template #default>
        <el-form
          :model="depFormData"
          ref="dialogFormRef"
          label-width="80"
          :rules="dialogFormRules"
        >
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="depFormData.name"></el-input>
          </el-form-item>
          <el-form-item label="负责人" prop="head">
            <!-- <el-input v-model="depFormData.head"></el-input> -->
            <el-select v-model="depFormData.head">
              <el-option
                v-for="item in depUserList"
                :key="item._id"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button type="default" @click="close">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.Department {
  .el-card {
    margin-bottom: 20px;
    .el-input {
      width: 140px;
      margin-right: 10px;
    }
    .el-pagination {
      margin-top: 20px;
    }
  }
}
</style>
